package com.fch.sdlibrary.controller;

import com.fch.sdlibrary.api.BaseResponse;
import com.fch.sdlibrary.entity.Book;
import com.fch.sdlibrary.entity.BookClazz;
import com.fch.sdlibrary.service.BookClazzService;
import com.fch.sdlibrary.service.BookService;
import com.fch.sdlibrary.service.HistoryService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @program: sdlibrarySpring
 * @description: 管理员控制页
 * @CreatedBy: fch
 * @create: 2022-05-13 22:38
 **/
@CrossOrigin
@RestController
@RequestMapping("Admin")
public class AdminController {
    private BaseResponse baseResponse;
    @Autowired
    private BookService bookService;
    @Autowired
    private BookClazzService bookClazzService;
    @Autowired
    private HistoryService historyService;


    /**
    * @Author: fch
    * @Description: 查询单个图书
    * @DateTime: 14:44 15/5/2022
    * @Params: [id]
    * @Return: com.fch.sdlibrary.api.BaseResponse
    **/
    @PostMapping("QueryBook")
    public BaseResponse queryBook(@RequestParam("id") String id) {
        baseResponse = new BaseResponse();
        if ("".equals(id) || id == null) {
            baseResponse.setMsg("查询为空");
            return baseResponse;
        }
        Book book = bookService.queryBookById(id);
        if (book != null) {
            HashMap data = new HashMap();
            data.put("book", book);
            List<BookClazz> bookClazzes;
            bookClazzes = bookClazzService.getBookClazzList(book.getBookClassCode());
            data.put("classList", bookClazzes);
            baseResponse.setData(data);
        }
        return baseResponse;
    }


    /**
     * 添加图书
     * @param bookStr
     * @param file
     * @param request
     * @return
     */
    @PostMapping("AddBook")
    public BaseResponse addBook(@RequestParam("book") String bookStr,
                                @RequestParam("myFile") MultipartFile file, HttpServletRequest request) {
        baseResponse = new BaseResponse();
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(int.class, new IntTypeAdapter())
                .registerTypeAdapter(Integer.class, new IntTypeAdapter()).create();
        Book book = gson.fromJson(bookStr, Book.class);
        if ("".equals(book.getBookClassCode()))
            book.setBookClassCode("01");
        book.setBookIsbn(book.getBookIsbn().replace("-",""));
        Book newBook = bookService.addToBook(book);
        if (newBook != null && !file.isEmpty()) {
            String imgPath = "img/" + newBook.getBookClassCode() + "/";
            imgPath = upImg(imgPath, newBook.getBookId().toString(), file, request).substring(4);
            if ("创建失败".equals(imgPath)) {
                baseResponse.setMsg("创建失败");
                return baseResponse;
            }
            newBook.setBookImg(imgPath);
            if (bookService.updateImg(newBook) > 0) {
                baseResponse.setMsg("创建成功");
                return baseResponse;
            }
        } else {
            baseResponse.setCode(200);
            baseResponse.setMsg("添加失败");
            return baseResponse;
        }
        return baseResponse;
    }

    /**
     * 添加一级分类
     * @param params
     * @return
     */
    @PostMapping("AddClassL1")
    public BaseResponse addClassL1(@RequestBody HashMap<String, String> params) {
        baseResponse = new BaseResponse();
        String newL1 = params.get("newL1");
        if (newL1 == null || "".equals(newL1)) {
            baseResponse.setMsg("请输入名称");
            return baseResponse;
        }
        BookClazz bookClazz = new BookClazz();
        bookClazz.setClassificationName(newL1);
        bookClazz.setClassLayer(1);
        if (bookClazzService.AddClazzL1(bookClazz))
            baseResponse.setMsg("添加成功");
        else
            baseResponse.setMsg("添加失败");
        return baseResponse;
    }

    /**
     * 添加二级分类
     * @param params
     * @return
     */
    @PostMapping("AddClassL2")
    public BaseResponse addClassL2(@RequestBody HashMap<String, String> params) {
        baseResponse = new BaseResponse();
        String newL2 = params.get("newL2");
        String bookCode = params.get("bookCode");
        if (newL2 == null || "".equals(newL2) || "-1".equals(bookCode) || "01".equals(bookCode)) {
            baseResponse.setMsg("请输入名称或未选择分类");
            return baseResponse;
        }
        if (!bookClazzService.isExist(bookCode)) {
            baseResponse.setMsg("父分类不存在");
            return baseResponse;
        }
        BookClazz bookClazz = new BookClazz();
        bookClazz.setClassParent(bookCode);
        bookClazz.setClassificationName(newL2);
        bookClazz.setClassLayer(2);

        if (bookClazzService.AddClazzChild(bookClazz))
            baseResponse.setMsg("添加成功");
        else
            baseResponse.setMsg("添加失败");
        return baseResponse;
    }

    /**
     * 添加三级分类
     * @param params
     * @return
     */
    @PostMapping("AddClassL3")
    public BaseResponse addClassL3(@RequestBody HashMap<String, String> params) {
        baseResponse = new BaseResponse();
        String newL3 = params.get("newL3");
        String bookCode = params.get("bookCode");
        if (newL3 == null || "".equals(newL3) || "-1".equals(bookCode) || "01".equals(bookCode)) {
            baseResponse.setMsg("请输入名称或未选择分类");
            return baseResponse;
        }
        if (!bookClazzService.isExist(bookCode)) {
            baseResponse.setMsg("父分类不存在");
            return baseResponse;
        }
        BookClazz bookClazz = new BookClazz();
        bookClazz.setClassParent(bookCode);
        bookClazz.setClassificationName(newL3);
        bookClazz.setClassLayer(3);
        if (bookClazzService.AddClazzChild(bookClazz))
            baseResponse.setMsg("添加成功");
        else
            baseResponse.setMsg("添加失败");
        return baseResponse;
    }

    /**
     * 更新图书
     * @param bookStr
     * @param file
     * @param request
     * @return
     */
    @PostMapping("UpdateBook")
    public BaseResponse updateBook(@RequestParam("book") String bookStr,
                                   @RequestParam(value = "myFile", required = false) MultipartFile file, HttpServletRequest request) {
        baseResponse = new BaseResponse();
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(int.class, new IntTypeAdapter())
                .registerTypeAdapter(Integer.class, new IntTypeAdapter()).create();
        Book book = gson.fromJson(bookStr, Book.class);
        book.setBookIsbn(book.getBookIsbn().replace("-",""));
        book = bookService.updateBook(book);
        if (book == null) {
            baseResponse.setMsg("修改失败");
            return baseResponse;
        }
        if (file != null) {
            String imgPath = "img/" + book.getBookClassCode() + "/";
            imgPath = upImg(imgPath, book.getBookId().toString(), file, request).substring(4);
            book.setBookImg(imgPath);
            bookService.updateImg(book);
        }
        baseResponse.setMsg("修改成功");
        return baseResponse;
    }

    /**
     * 图片回显
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("Upload")
    public BaseResponse upload(@RequestParam("myFile") MultipartFile file, HttpServletRequest request) {
        baseResponse = new BaseResponse();
        if (!file.isEmpty()) {
            baseResponse.setData(upImg("img/0/", "1", file, request).substring(4));
        }
        return baseResponse;
    }

    @PostMapping("QueryHistory")
    public BaseResponse queryHistory() {
        baseResponse = new BaseResponse();
        baseResponse.setCode(200);
        baseResponse.setData(historyService.queryHistory());
        return baseResponse;
    }


    /**
     * 封装的添加图片
     *
     * @param childPath
     * @param imgName
     * @param file
     * @param request
     * @return
     */
    private String upImg(String childPath, String imgName, MultipartFile file, HttpServletRequest request) {
        //1.创建上传的文件存放的文件夹
        //得到存放文件的路径:静态资源路径+那你自己定义的"upload/2022-04-13/"
        //静态资源路径：如果resources下面有public或者static文件夹，那么我们就把它当成静态资源路径（idea需要设置），如过没有，才会用那个临时文件夹
        String path = request.getServletContext().getRealPath(childPath);
        //创建文件夹，但凡你要操作文件或者文件夹，你都要先创建它对应的File对象
        File desDir = new File(path);
        if (!desDir.exists()) {
            //mkdirs()和mkdir()区别
            desDir.mkdirs();
        }
        //2.上传文件
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String desFileName = imgName + suffix;
        //但凡你要操作文件或者文件夹，你都要先创建它对应的File对象
        File desFile = new File(path, desFileName);
        try {
            file.transferTo(desFile);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建失败");
            return "创建失败";
        }
        String reFilePath = childPath + desFileName;
        return reFilePath;
    }


    /**
     * gsonInt适配器
     */
    class IntTypeAdapter extends TypeAdapter<Number> {

        @Override
        public void write(JsonWriter out, Number value)
                throws IOException {
            out.value(value);
        }

        @Override
        public Number read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            try {
                String result = in.nextString();
                if ("".equals(result)) {
                    return null;
                }
                return Integer.parseInt(result);
            } catch (NumberFormatException e) {
                throw new JsonSyntaxException(e);
            }
        }
    }

}
